package com.seqb.system.controller;

import com.google.code.kaptcha.Constants;
import com.seqb.annotation.Log;
import com.seqb.common.ResultVo;
import com.seqb.common.Tree;
import com.seqb.common.config.SeqbConfig;
import com.seqb.common.controller.BaseController;
import com.seqb.manage.menu.domain.MenuDO;
import com.seqb.manage.menu.service.MenuService;
import com.seqb.utils.Md5Utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author lilinshen
 * @title 登录的controller
 * @description 请填写相关描述
 * @date 2019/11/12
 */
@Controller
public class LoginController extends BaseController {
    @Autowired
    MenuService menuService;
    @Autowired
    SeqbConfig seqbConfig;

    @GetMapping({"/", ""})
    String welcome(Model model) {
        return "redirect:/index";
    }

    @Log("请求访问主页")
    @GetMapping({"/index"})
    String index(Model model) {
        List<Tree<MenuDO>> menus = menuService.listTree(getUserId());
        model.addAttribute("menus", menus);
        model.addAttribute("name", getUser().getAccount());
        return "index";
    }

    @GetMapping("/login")
    String login(Model model) {
        //验证码是否开启
        model.addAttribute("kaptchaOpen", seqbConfig.isKaptchaOpen());
        return "login";
    }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    ResultVo ajaxLogin(String username, String password, String kaptcha, HttpServletRequest request) {
        //验证验证码是否正确
        if (seqbConfig.isKaptchaOpen()) {
            String code = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (StringUtils.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
                return ResultVo.error("验证码错误");
            }
        }
        password = Md5Utils.encrypt(password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return ResultVo.ok();
        } catch (AuthenticationException e) {
            return ResultVo.error(e.getMessage());
        }
    }

    @GetMapping("/main")
    String main(HttpServletRequest request) {
        return "main";
    }

}
